package com.weilive.pay.service.ali;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.weilive.core.utils.HttpUtils;
import com.weilive.core.utils.MD5Utils;
import com.weilive.pay.dao.mapper.UserCashMapper;
import com.weilive.pay.dao.model.AddEMoney;
import com.weilive.pay.dao.model.CashLog;
import com.weilive.pay.dao.model.CashTx;
import com.weilive.pay.dao.model.UserCash;
import com.weilive.pay.dao.model.UserInfo;
import com.weilive.pay.msg.ToPayMsg;
import com.weilive.pay.service.CashTemplate;

@Service
public class AlipayService {
	private static final Logger logger = LoggerFactory.getLogger(AlipayService.class);
	@Autowired
	private UserCashMapper userCashDao;
	// 付费资源
	@Autowired
	private CashTemplate cashTemplate;

	private String getLogKey(String key) {
		try {
			return MD5Utils.encryptToHex(key);
		} catch (Exception e) {
		}
		return UUID.randomUUID().toString();
	}

	// 没用事物
	public String checkAndSaveLog(Map<String, String> params) {
		try {
			// 交易状态
			String trade_status = params.get("trade_status");
			if (trade_status.equals("WAIT_BUYER_PAY")) {
				logger.info("支付忽略,trade_status=" + trade_status);
				return "ok";
			}
			// 内容
			String body = params.get("body");

			JSONObject obj = (JSONObject) JSONObject.parse(body);

			String userId = obj.getString("userId");

			String key = getLogKey(params.toString());

			CashLog log = userCashDao.getCashLog(key);
			if (log == null) {
				log = new CashLog();
				log.setId(key);
				log.setRecipe(params.toString());
				log.setUser_id(Long.parseLong(userId));
				log.setStatus(0);
				userCashDao.saveCashLog(log);
			}
			// 已到账
			if (log.getStatus() == 1) {
				// 支付成功了
				return "ok";
			}
		} catch (Exception e) {
		}

		return "fail";
	}

	@Transactional
	public String pay(Map<String, String> params) {

		String logKey = getLogKey(params.toString());

		String trade_status = params.get("trade_status");
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号
		String out_trade_no = params.get("out_trade_no");
		// 支付宝交易号
		String trade_no = params.get("trade_no");

		String goodsCount = params.get("quantity");

		String price = params.get("price");
		String total_fee = params.get("total_fee");
		String seller_id = params.get("seller_id");
		String seller_email = params.get("seller_email");
		String buyer_id = params.get("buyer_id");
		String buyer_email = params.get("buyer_email");
		// 内容
		String body = params.get("body");

		JSONObject obj = (JSONObject) JSONObject.parse(body);
		String userId = obj.getString("userId");
		String goodsId = obj.getString("produceId");
		// String userName = obj.getString("userAlias");
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		// 忽略
		if (AlipayConfig.verify(params)) {// 验证成功

			if (trade_status.equals("TRADE_FINISHED")) {
			} else if (trade_status.equals("TRADE_SUCCESS")) {
				UserCash userCash = userCashDao.getUserCash(out_trade_no);

				double costMoney = Double.parseDouble(total_fee);
				if (userCash == null) {
					userCash = new UserCash();
					userCash.setOutTradeNo(out_trade_no);
					userCash.setTradeNo(trade_no);
					userCash.setUserId(Long.parseLong(userId));
					userCash.setGoodsId(goodsId);
					userCash.setGoodsCount(goodsCount);
					userCash.setPrice(Double.parseDouble(price));
					userCash.setTotalFee(costMoney);
					userCash.setSellerId(seller_id);
					userCash.setSellerEmail(seller_email);
					userCash.setBuyerId(buyer_id);
					userCash.setBuyerEmail(buyer_email);
					userCash.setPayStatus(1);
					userCash.setExt("Alipay");
					userCash.setCdate(new Date());
					userCashDao.insertSelective(userCash);

					// 加钱操作
					int mibi = Math.max(1, (int) (costMoney * 10));
					CashTx cashTx = cashTemplate.getCashTx(goodsId);
					if (cashTx != null) {
						double ratio = cashTx.getCredit() / cashTx.getCost();

						if (costMoney == cashTx.getCost()) {
							mibi = cashTx.getCredit();
						} else {
							mibi = Math.max(1, (int) (costMoney * ratio));
						}
					}
					// call add_e_money(userId, mibi)
					AddEMoney result = userCashDao.addEMoney(Long.parseLong(userId), (long) mibi,
							userCash.getTradeId());

					userCashDao.useCashSuccess(logKey);

					logger.info("userId={},用户可得mibi={}, out_trade_no={}", new Object[] { userId, mibi, out_trade_no });

					if (result.getIs_success_flag().equals("N")) {
						throw new RuntimeException(result.getErr_msg());
					}
				}
			}
			return "success";
		}
		return "fail";
	}

	@Transactional
	public String query(String out_trade_no) {
		UserCash userCash = userCashDao.getUserCash(out_trade_no);
		if (userCash == null) {
			// 还没通知到
			return new ToPayMsg("0", "还没入帐", null, null).toString();
		}
		UserInfo userInfo = userCashDao.getUserInfo(userCash.getUserId());

		return new ToPayMsg("1", null, userInfo.getE_money(), userInfo.getVip_expiration()).toString();
	}

	public static void main(String[] args) throws Exception {

		String md5 = "iirdarf2an9odvgl30gfvfqvr1j3r0oq";

		String service = "single_trade_query";
		String partner = AlipayConfig.partner;
		String _input_charset = "utf-8";

		String out_trade_no = "2G5F40L781M0IM4";

		String url = "https://mapi.alipay.com/gateway.do";

		Map<String, String> map = new HashMap<String, String>();
		map.put("service", service);
		map.put("partner", partner);
		map.put("_input_charset", _input_charset);
		map.put("out_trade_no", out_trade_no);

		String strSign = AlipayConfig.createLinkString(map);

		String md5Sign = strSign + md5;

		System.out.println("md5Sign=" + md5Sign);

		String sign_type = "MD5";

		String sign = MD5Utils.encryptToHex(md5Sign);

		System.out.println("sign=" + sign + ":length=" + sign.length());

		String get = strSign + "&sign_type=" + sign_type + "&sign=" + sign;
		System.out.println("get=" + get);
		// String out = HttpUtils.HttpGetGo(url + get);
		String out = HttpUtils.HttpPostGo(url, get);
		System.out.println(out);

	}
}
